package com.hxgis.oc.product.file;

import cn.hutool.http.HttpUtil;
import com.hxgis.oc.product.base.ConvertTask;
import com.hxgis.oc.product.base.ProduceTask;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@Slf4j
public class DownloadTask extends ProduceTask {
    protected String url;
    protected List<ConvertTask> convertTaskList = new ArrayList<>();

    public DownloadTask(Long workID, String ds,File file) {
        super(workID,ds);
        outputFile = file;
        productType = FileProductManager.getFactoryName();
    }

    @Override
    public boolean producing() {
        boolean succeed;

        long size = 0;
        try{
            log.debug("{} start download {}",
                    this.getClass().getSimpleName(),
                    outputFile.getAbsolutePath());
            size = HttpUtil.downloadFile(url, outputFile);
        }
        catch(Exception e){
            log.error(e.getMessage());
        }
        finally {
            succeed = size > 0;
            if(succeed && checker != null){
                succeed = (Boolean) checker.apply(this);
            }
            if(!succeed){
                outputFile.delete();
                log.debug("{} fail download {}",
                        this.getClass().getSimpleName(),
                        outputFile.getAbsolutePath());
            }
        }
        return succeed;
    }

    public void addConvertTask(ConvertTask task){
        convertTaskList.add(task);
    }

    public ConvertTask getConvertTask(Object convClass) {
        for(ConvertTask task : convertTaskList)
        {
            if(task.getClass() == convClass)
            {
                return task;
            }
        }

        return null;
    }

    public void runSync() {
        for(ConvertTask task : convertTaskList)
        {
            task.setAsync(false);
        }
        this.run();
    }
}
